package pool;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;

import com.mysql.jdbc.Driver;

public class PoolManager {
	private static PoolManager poolManager;
	private int clients;
	private PrintWriter log;
	private DBConnectionPool pool;
	private Driver driver;

	// 释放一个连接
	public void freeConnection(Connection con) {
		if (pool != null) {
			pool.freeConnection(con);
		}
	}

	// 关闭所有连接
	public synchronized void release() {
		if (--clients != 0)
			return;
		pool.release();
		try {
			DriverManager.deregisterDriver(driver);
		} catch (SQLException e) {
			e.printStackTrace();
			log(e, "无法撤消JDBC驱动程序的注册" + driver.getClass().getName());
		}
	}

	// 取得一个连接
	public Connection getConnection() {
		if (pool != null) {
			return pool.getConnection();
		}
		return null;
	}

	public Connection getConnection(long time) {
		if (pool != null) {
			return pool.getConnection(time);
		}
		return null;
	}

	private PoolManager() {
		try {
			driver = (Driver) Class.forName("").newInstance();
			pool=new DBConnectionPool("","","","", 2);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 单例返回一个管理
	public PoolManager newInstance() {
		if (null == poolManager) {
			poolManager = new PoolManager();
		}
		return poolManager;
	}

	private void init() {

	}

	private void log(String msg) {
		log.println(new Date() + ":" + msg);
	}

	private void log(Throwable e, String msg) {
		log.println(new Date() + ":" + msg);
		e.printStackTrace(log);
	}
}
